<%--
  Created by IntelliJ IDEA.
  User: xiaobao
  Date: 2024/12/24
  Time: 10:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="jakarta.tags.fmt" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>

<style>
    /* 整体页面背景设置为浅灰色系，营造简洁科技感 */
    body {
        font-family: Arial, sans-serif;
        background-color: #f0f0f5;
        margin: 0;
        padding: 0;
        color: #333;
    }

    /* 页面主容器，设置宽度、居中、内边距、背景色及轻微阴影效果 */
    .main-container {
        width: 60%;
        margin: 30px auto;
        padding: 20px;
        background-color: white;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        border-radius: 8px;
    }

    /* 标题样式，字体大小、加粗、颜色及下边距 */
    h1 {
        font-size: 24px;
        font-weight: bold;
        color: #007bff;
        margin-bottom: 15px;
    }

    /* 表单样式 */
    form {
        padding: 20px;
        border: 1px solid #ccc;
        border-radius: 5px;
        background-color: #f9f9f9;
    }

    /* 表单标签样式 */
    label {
        display: block;
        margin-bottom: 8px;
        font-weight: bold;
        color: #333;
    }

    /* 表单输入框样式 */
    input[type="text"],
    input[type="number"],
    input[type="date"],
    textarea {
        width: 100%;
        padding: 10px;
        margin-bottom: 15px;
        border: 1px solid #ccc;
        border-radius: 3px;
        box-sizing: border-box;
        transition: border-color 0.3s ease;
    }

    input[type="text"]:focus,
    input[type="number"]:focus,
    input[type="date"]:focus,
    textarea:focus {
        border-color: #007bff;
    }

    /* 下拉菜单样式 */
    select {
        width: 100%;
        padding: 10px;
        margin-bottom: 15px;
        border: 1px solid #ccc;
        border-radius: 3px;
        box-sizing: border-box;
        appearance: none;
        -webkit-appearance: none;
        -moz-appearance: none;
        background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23333"><path d="M7 10l5 5 5-5z"/></svg>') no-repeat right 10px center;
        background-size: 12px 12px;
    }

    /* 提交按钮样式 */
    input[type="submit"],
    .back-button {
        display: inline-block;
        text-decoration: none;
        padding: 10px 20px;
        border-radius: 3px;
        font-size: 16px;
        color: white;
        cursor: pointer;
        transition: background-color 0.3s ease, box-shadow 0.3s ease;
        margin-bottom: 10px;
    }

    input[type="submit"] {
        background-color: #28a745;
        box-shadow: 0 3px 6px rgba(0, 0, 0, 0.2);
    }

    input[type="submit"]:hover {
        opacity: 0.8;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
    }

    .back-button {
        background-color: #6c757d;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .back-button:hover {
        opacity: 0.8;
        box-shadow: 0 3px 6px rgba(0, 0, 0, 0.2);
    }

    /* 错误提示信息样式 */
    .error-message {
        color: #dc3545;
        margin-bottom: 10px;
        font-size: 14px;
        display: none;
    }

    /* 编号已存在提示信息样式 */
    .id-exists-message {
        color: #dc3545;
        margin-bottom: 10px;
        font-size: 14px;
        display: none;
    }

    /* 表单元素分组样式，增加元素之间的间距 */
    .form-group {
        margin-bottom: 30px;
    }

    /* 按钮容器样式，将按钮水平排列并添加间距 */
    .button-container {
        display: flex;
        justify-content: flex-end;
        gap: 20px;
        margin-top: 20px;
    }
</style>

<div class="main-container">
    <h1>添加商品信息</h1>
    <form action="good.action?action=save" method="post" id="addForm" onsubmit="return false">
        <div class="form-group">
            <label for="id">商品编号</label>
            <input type="text" id="id" name="id" required>
            <span class="error-message" id="idError">商品编号不能为空，且应为字母、数字组成，长度不超过20个字符</span>
            <span class="id-exists-message" id="idExistsError">该商品编号已存在，请重新输入</span>
        </div>

        <div class="form-group">
            <label for="categoryId">商品类别</label>
            <select id="categoryId" name="categoryId" required>
                <%-- 假设后端已将商品类别列表（categoryList）存放到请求作用域中，遍历生成选项 --%>
                <c:forEach items="${categoryList}" var="category">
                    <option value="${category.id}">${category.name}</option>
                </c:forEach>
            </select>
            <span class="error-message" id="categoryIdError">商品类别必须选择</span>
        </div>

        <div class="form-group">
            <label for="name">商品名称</label>
            <input type="text" id="name" name="name" required>
            <span class="error-message" id="nameError">商品名称不能为空，且长度不超过50个字符</span>
        </div>

        <div class="form-group">
            <label for="price">商品价格</label>
            <input type="number" step="0.01" id="price" name="price" required>
            <span class="error-message" id="priceError">商品价格不能为空，且请输入正确的价格格式，保留两位小数</span>
        </div>

        <div class="form-group">
            <label for="description">商品描述</label>
            <textarea id="description" name="description" required></textarea>
            <span class="error-message" id="descriptionError">商品描述不能为空</span>
        </div>

        <div class="form-group">
            <label for="inPrice">商品进价</label>
            <input type="number" step="0.01" id="inPrice" name="inPrice" required>
            <span class="error-message" id="inPriceError">商品进价不能为空，且请输入正确的价格格式，保留两位小数</span>
        </div>

        <div class="form-group">
            <label for="number">商品剩余数量</label>
            <input type="number" id="number" name="number" required>
            <span class="error-message" id="numberError">商品剩余数量不能为空，且应为正整数</span>
        </div>

        <div class="form-group">
            <label for="createDate">商品生产日期</label>
            <input type="date" id="createDate" name="createDate" required>
            <span class="error-message" id="createDateError">商品生产日期不能为空</span>
        </div>

        <div class="form-group">
            <label for="shelfLife">商品保质期</label>
            <input type="number" id="shelfLife" name="shelfLife" required>
            <span class="error-message" id="shelfLifeError">商品保质期不能为空，且应为正整数</span>
        </div>

        <div class="form-group">
            <label for="supplier_id">供应商</label>
            <select id="supplier_id" name="supplier_id" required>
                <%-- 假设后端已将供应商列表（supplierList）存放到请求作用域中，遍历生成选项 --%>
                <c:forEach items="${supplierList}" var="supplier">
                    <option value="${supplier.id}">${supplier.name}</option>
                </c:forEach>
            </select>
            <span class="error-message" id="supplier_idError">供应商必须选择</span>
        </div>

        <div class="button-container">
            <input type="submit" value="提交">
            <a href="good.action?action=list" class="back-button">返回</a>
        </div>
    </form>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
        $(document).ready(function () {
            // 商品编号输入时，检查是否已存在
            $('#id').on('input', function () {
                var id = $(this).val();
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var exists = JSON.parse(xhr.responseText);
                        if (exists) {
                            $('#idExistsError').show();
                        } else {
                            $('#idExistsError').hide();
                        }
                    }
                };
                xhr.open('GET', 'checkGoodIdExists.action?id=' + id, true);
                xhr.send();
            });

            // 表单提交时进行验证
            $('#addForm').submit(function (e) {
                var isValid = true;
                var id = $('#id').val();
                var categoryId = $('#categoryId').val();
                var name = $('#name').val();
                var price = $('#price').val();
                var description = $('#description').val();
                var inPrice = $('#inPrice').val();
                var number = $('#number').val();
                var createDate = $('#createDate').val();
                var shelfLife = $('#shelfLife').val();
                var supplier_id = $('#supplier_id').val();

                // 商品编号验证
                if (id === '') {
                    $('#idError').show();
                    isValid = false;
                } else if (!/^[a-zA-Z0-9]{1,20}$/.test(id)) {
                    $('#idError').html("商品编号格式不正确，只能包含字母、数字，长度不超过20个字符");
                    $('#idError').show();
                    isValid = false;
                } else {
                    $('#idError').hide();
                }

                // 商品类别验证
                if (categoryId === '') {
                    $('#categoryIdError').show();
                    isValid = false;
                } else {
                    $('#categoryIdError').hide();
                }

                // 商品名称验证
                if (name === '') {
                    $('#nameError').show();
                    isValid = false;
                } else if (name.length > 50) {
                    $('#nameError').html("商品名称应简洁明了，长度不超过50个字符");
                    $('#nameError').show();
                    isValid = false;
                } else {
                    $('#nameError').hide();
                }

                // 商品价格验证
                if (price === '') {
                    $('#priceError').show();
                    isValid = false;
                } else if (!/^\d+(\.\d{1,2})?$/.test(price)) {
                    $('#priceError').html("请输入正确的价格格式，保留两位小数");
                    $('#priceError').show();
                    isValid = false;
                } else {
                    $('#priceError').hide();
                }

                // 商品描述验证
                if (description === '') {
                    $('#descriptionError').show();
                    isValid = false;
                } else {
                    $('#descriptionError').hide();
                }

                // 商品进价验证
                if (inPrice === '') {
                    $('#inPriceError').show();
                    isValid = false;
                } else if (!/^\d+(\.\d{1,2})?$/.test(inPrice)) {
                    $('#inPriceError').html("请输入正确的价格格式，保留两位小数");
                    $('#inPriceError').show();
                    isValid = false;
                } else {
                    $('#inPriceError').hide();
                }

                // 商品剩余数量验证
                if (number === '') {
                    $('#numberError').show();
                    isValid = false;
                } else if (!/^\d+$/.test(number)) {
                    $('#numberError').html("商品剩余数量不能为空，且应为正整数");
                    $('#numberError').show();
                    isValid = false;
                } else {
                    $('#numberError').hide();
                }

                // 商品生产日期验证
                if (createDate === '') {
                    $('#createDateError').show();
                    isValid = false;
                } else {
                    $('#createDateError').hide();
                }

                // 商品保质期验证
                if (shelfLife === '') {
                    $('#shelfLifeError').show();
                    isValid = false;
                } else if (!/^\d+$/.test(shelfLife)) {
                    $('#shelfLifeError').html("商品保质期不能为空，且应为正整数");
                    $('#shelfLifeError').show();
                    isValid = false;
                } else {
                    $('#shelfLifeError').hide();
                }

                // 供应商验证
                if (supplier_id === '') {
                    $('#supplier_idError').show();
                    isValid = false;
                } else {
                    $('#supplier_idError').hide();
                }

                if (!isValid) {
                    e.preventDefault();
                } else {
                    var formData = $(this).serialize();
                    $.ajax({
                        url: 'good.action?action=save',
                        type: 'POST',
                        data: formData,
                        success: function (result) {
                            console.log(result);
                            if (result.startsWith("保存成功")) {
                                Swal.fire({
                                    icon: 'success',
                                    title: '成功',
                                    text: '商品保存成功',
                                }).then(function () {
                                    // 刷新到指定页面，例如 index.html
                                    window.location.href = 'good.action?action=list';
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: '失败',
                                    text: result
                                });
                            }
                        },
                        error: function (xhr, status, error) {
                            Swal.fire({
                                icon: 'error',
                                title: '请求出错',
                                text: '出现网络问题或服务器错误，请稍后再试'
                            });
                        }
                    });
                }
            });
        });
    </script>
</div>